#include <stdio.h>  
#include <termios.h> //POSIX终端控制定义  
#include <unistd.h> //Unix 标准函数定义  
#include <stdlib.h>
#include <signal.h> // This line must be written.

#include <sys/ioctl.h> 
#include <sys/types.h> 
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
  
#define PWM_IOCTL_SET_FREQ  1  
#define PWM_IOCTL_STOP   0  
  
  
unsigned int muiscscore[]={239,213,189,179,159,142,127,120,  
                           120,106,95,90,80,71,64,60,  
                           60,53,47,45,40,36,32,30};  
unsigned int sszymmh[]={13,3, 12,1, 10,2, 12,2, 16,2, 13,1, 12,1, 13,4,  
                         10,2, 12,1, 13,1, 12,2, 10,1, 9,1, 8,1, 5,1,   
                         12,1, 10,1, 9,4, 9,3, 10,1, 12,2, 12,1, 13,1, 10,3,   
                         9,1, 8,4, 12,3, 10,1, 9,1, 8,1, 5,1, 9,1, 5,4, 0,0,};  
  
static int fd = -1;  
  
static void close_buzzer(void);  
static void open_buzzer(void) //打开蜂鸣器  
{
  fd = open("/dev/fl2440_pwm", O_RDWR | O_NONBLOCK); //打开pwm设备驱动文件  
  if (fd < 0) {  
    perror("open fl2440_pwm device"); //打开错误，则终止进程。退出参数为1  
    exit(1);  
  }
  
  // any function exit call will stop thebuzzer  
  atexit(close_buzzer); //退出回调close_buzzer  
}
  
static void close_buzzer(void) //关闭蜂鸣器  
{  
  if (fd >= 0) {  
    ioctl(fd, PWM_IOCTL_STOP); //停止蜂鸣器  
    close(fd); //关闭设备驱动文件  
    fd = -1;  
  }
}
  
static void set_buzzer_freq(int freq)  
{
 // this IOCTL command is the key to set frequency  
 int ret = ioctl(fd, PWM_IOCTL_SET_FREQ, freq); //设置频率  
   
}

void delay(unsigned int t)  
{  
  unsigned int t1;  
  unsigned long t2;  
  for(t1=0;t1<t*137;t1++)  
     {  
  
       for(t2=0;t2<58000;t2++);                                  
     }  
}

void sig_handle(int sig)
{
    if (SIGINT == sig)
    {
      close_buzzer();  
      exit(0);
    }
}
  
int main(int argc,char **argv)  
{  
 int freq;  
 unsigned int k;  
 int i=0;  
 unsigned int time;
 signal(SIGINT, sig_handle); // register "Ctrl + c" event handling callback, and if considering the security of call, it is replaced by sigaction.  
   
 open_buzzer(); //打开蜂鸣器
   
   
  while(1)  
  {  
    k=sszymmh[i];  
    freq=muiscscore[k];
    printf("PWM freq :%d\n",freq);  
    time=sszymmh[i+1];
    printf("PWM freq :%d\n",time);  
    set_buzzer_freq(freq); //设置蜂鸣器频率  
    //sleep(freq/2);  
     
    delay(time);
    i=i+2;
    if(i==70)
    {
      close_buzzer();  
      exit(0);
      i=0;
    }
  }
}


